<template>
  <div class="app-container">
    <div class="body-container mt0">
      <div class="operation-bar">
        <div class="bar-title">
          {{ projectName }} - 学员列表
        </div>
        <div class="bar-btn__wrapper">
          <div class="bar-btn" @click="handleUploadFile"><i class="el-icon-upload2"></i>导入</div>
          <div class="bar-btn" @click="handleAdd"><i class="el-icon-plus"></i>新增</div>
          <div class="bar-btn" @click="handleDelSel"><i class="el-icon-delete"></i>批量删除</div>
        </div>
      </div>

      <el-table v-loading="loading" stripe :data="dataList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index" label="#" align="center" min-width="100"></el-table-column>
        <el-table-column label="姓名" prop="personnelName" align="center" min-width="200">
          <template slot-scope="scope">
            <el-link @click="handleToDetail(scope.row)" :underline="false" type="primary">{{
              scope.row.personnelName }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="单位" align="center" min-width="200">
          <div slot-scope="scope">
            {{ getDeptName(scope.row.personnelId,scope.row.unitCode) }}
          </div>
        </el-table-column>
        <el-table-column label="性别" align="center" min-width="200">
          <div slot-scope="scope">
            {{ scope.row.gender === 1 ? '男' : '' }}
            {{ scope.row.gender === 2 ? '女' : '' }}
            {{ scope.row.gender === 0 ? '未知' : '' }}
          </div>
        </el-table-column>
        <el-table-column label="年龄" align="center" prop="age" min-width="200"></el-table-column>
        <el-table-column label="专业" align="center" prop="major" min-width="200"></el-table-column>

        <el-table-column label="操作" align="center" min-width="240" class-name="small-padding fixed-width">
          <div class="table-option" slot-scope="scope" v-if="scope.row.roleId !== 1">
            <span class="danger" @click="handleDelete(scope.row)" v-if="end === 'false'">删除</span>
          </div>
        </el-table-column>
      </el-table>

      <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </div>

    <editPerson :title="editTitle" :projectId="projectId" :editType="editType" :editData="editData" :visible.sync="editDialog" @close="getList">
    </editPerson>
    <UserDetail :id="personnelId" :visible.sync="userDialog"></UserDetail>

    <el-dialog title="导入成绩" :visible.sync="uploadialog" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="fileHeaders" action="#" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-change="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="handleDownLoad2">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="uploadDisable" :loading="uploadDisable" @click="submitFileForm">确
          定</el-button>
        <el-button @click="uploadialog = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { queryProjectPersonnelList, delTrainingSubjectPersonnel, uploadPerson } from "@/api/subject";
import editPerson from './components/editPerson.vue'
import { getDeptName, getDeptNameStr,getParentId } from "@/utils/ruoyi";
import UserDetail from '@/components/userDetail.vue'
import { getToken } from "@/utils/auth";
import ExportExcel from '@/utils/excel';
import XLSX from 'xlsx';

export default {
  name: "file",
  dicts: ['sys_user_major_code'],
  components: {
    editPerson,
    UserDetail
  },
  computed: {
    deptList () {
      return this.$store.state.user.deptList
    },
    deptTreeList () {
      return this.$store.state.user.deptTreeList
    },
    userList () {
      return this.$store.state.user.userList
    }
  },
  data () {
    return {
      uploadDisable: false,
      fileHeaders: {
        Authorization: "Bearer " + getToken()
      },
      upload: {
        isUploading: false,
        updateSupport: 0,
        url: process.env.VUE_APP_BASE_API + '/equipment/import',
      },
      uploadialog: false,
      userDialog: false,
      personnelId: '',
      end: false,
      editType: 'add',
      editData: {},
      total: 0,
      editTitle: "",
      editDialog: false,
      dataList: [],
      loading: true,
      total: 0,
      projectId: '',
      projectName: '',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      fileJson: [],
      dateRange: [],
      multipleSelection: []
    };
  },
  created () {
    this.projectId = this.$route.query.projectId || ''
    this.projectName = this.$route.query.projectName || ''
    this.end = this.$route.query.end
    this.getList();
  },
  methods: {
    handleUploadFile1 () {

    },
    // 导入文件
    handleUploadFile () {
      this.uploadialog = true
    },
    handleFileUploadProgress (event, file, fileList) {
      this.upload.isUploading = true;
      console.log(file)
    },
    // // 文件上传成功处理
    async handleFileSuccess (file, fileList) {
      let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
      let size = file.size / 1024 / 1024;
      if (
        extension !== "xlsx" &&
        extension !== "xlsm" &&
        extension !== "xltx" &&
        extension !== "xltm" &&
        extension !== "xlsb" &&
        extension !== "xls" &&
        extension !== "xlam" &&
        extension !== "csv"
      ) {
        this.$message.warning("只能Excel的文件，请重新上传");
        this.fileList = [];
        return;
      }
      if (size > 10) {
        this.$message.warning("文件大小不得超过10M，请重新上传");
        this.fileList = [];
        return;
      }
      this.fileJson = []
      this.file2Xce(file).then(async (tabJson) => {
        if (tabJson && tabJson.length > 0) {
          let tmpList = tabJson[0].sheet || []
          tmpList.map(item => {
            if (item['编号']) {
              let obj = {
                personnelUnitNum: item['编号'],
                personnelName: item['姓名'],
              }
              this.fileJson.push(obj)
            }
          })

        }
      })
    },
    // 批量导入客户文件转excel
    file2Xce (file) {
      return new Promise(function (resolve) {
        const reader = new FileReader()
        reader.onload = function (e) {
          const data = e.target.result
          this.wb = XLSX.read(data, {
            type: 'binary',
          })
          const result = []
          this.wb.SheetNames.forEach((sheetName) => {
            result.push({
              sheetName: sheetName,
              sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName]),
            })
          })
          resolve(result)
        }
        reader.readAsBinaryString(file.raw)
      })
    },
    async handleDownLoad2 () {
      let a = document.createElement('a')
      a.href = '/static/moban.xlsx'
      a.download = '导入学员模板.xlsx'
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
      a.remove()
    },
    // // 提交上传文件
    async submitFileForm () {
      this.uploadDisable = true;
      let res = await uploadPerson({
        personnelInfos: this.fileJson,
        trainingProjectId: this.projectId
      })
      if (res.code === 200) {
        this.uploadialog = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.uploadDisable = false;
        this.$message.success('导入成功！')
        this.getList();
      } else {
        this.$modal.msgWarning(res.msg);
      }

    },
    handleToDetail (row) {
      this.userDialog = true;
      console.log(row.personnelId)
      this.personnelId = String(row.personnelId)
    },
    getDeptName (id,unitCode) {
      
      return getDeptNameStr(this.userList, id)
    },
    handleSelectionChange (val) {
      this.multipleSelection = val;
    },
    // 新增
    handleAdd () {
      this.editTitle = "新增学员";
      this.editType = 'add'
      this.editDialog = true;
    },
    // 编辑
    handleEdit (row) {
      this.editTitle = "编辑学员";
      this.editType = 'edit'
      this.editData = row
      this.editDialog = true;
    },
    // 查询
    async getList () {
      this.loading = true;
      this.queryParams.projectId = this.$route.query.projectId || ''
      const res = await queryProjectPersonnelList(this.addStartDateRange(this.queryParams, this.dateRange))
      this.loading = false;
      if (res.code === 200) {
        this.getNewList(res.rows || [])
        this.total = res.total || 0;
      } else {
        this.dataList = [];
        this.total = 0;
      }
    },
    getNewList (rowList) {
      this.userList.map(userItem => {
        rowList.map(item => {
          if (userItem.id === item.personnelId) {
            let obj = this.dict.type.sys_user_major_code.find(codeItem => {
              return codeItem.value === userItem.majorCode
            })
            console.log(obj)
            if (obj) {
              item.major = obj.label || ''
            }
            item.age = userItem.age || ''
            item.gender = userItem.gender || ''
          }
        })
      })

      this.dataList = rowList
    },
    // 查询
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 导入文件
    handleUploadFile () {
      this.uploadialog = true
    },
    // 重置
    resetQuery () {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      }
      this.dateRange = []
      this.handleQuery();
    },
    handleDelSel () {
      let idList = []
      if (this.multipleSelection.length <= 0) {
        this.$modal.msgWarning("请选择要删除的数据");
        return
      } else {
        this.multipleSelection.map(item => {
          idList.push(item.personnelId)
        })
        this.$modal.confirm('是否确认删除?').then(() => {
          return delTrainingSubjectPersonnel({
            trainingProjectId: this.projectId,
            personnelId: idList
          });
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => { });
      }
    },
    // 删除
    handleDelete (row) {
      let personnelId = [row.personnelId]
      this.$modal.confirm('是否确认删除?').then(() => {
        return delTrainingSubjectPersonnel({
          trainingProjectId: this.projectId,
          personnelId
        });
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    }
  }
};
</script>